package cn.edu.xjtu.daily.April.day_4_14;

import java.util.*;

/**
 * @author Hydrion-QLz
 * @date 2022-04-14 13:06
 * @description P1305 新二叉树 : https://www.luogu.com.cn/problem/P1305
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Map<Character, TreeNode> map = new HashMap<>();
        TreeNode rootNode = null;

        // 构造二叉树
        for (int i = 0; i < n; i++) {
            String str = sc.next();
            char root = str.charAt(0);
            char left = str.charAt(1);
            char right = str.charAt(2);
            TreeNode node = map.getOrDefault(root, new TreeNode(root));
            if (rootNode == null) {
                rootNode = node;
            }
            if (left != '*') {
                TreeNode leftNode = new TreeNode(left);
                node.left = leftNode;
                map.put(left, leftNode);
            }
            if (right != '*') {
                TreeNode rightNode = new TreeNode(right);
                node.right = rightNode;
                map.put(right, rightNode);
            }
            map.put(root, node);
        }
        sc.close();

        // preOrderRecursion(rootNode);
        preOrder(rootNode);
    }

    /**
     * 前序遍历非递归实现，其实就是自己维护一个栈
     *
     * @param rootNode
     */
    private static void preOrder(TreeNode rootNode) {
        Deque<TreeNode> stack = new LinkedList<>();
        stack.addLast(rootNode);
        while (!stack.isEmpty()) {
            TreeNode node = stack.removeLast();
            System.out.print(node.val);
            // 注意顺序，这里必须要先加入右节点，否则的话就会先去遍历右子树了
            if (node.right != null) {
                stack.addLast(node.right);
            }
            if (node.left != null) {
                stack.addLast(node.left);
            }
        }
    }


    /**
     * 递归形式前序遍历
     *
     * @param rootNode
     */
    private static void preOrderRecursion(TreeNode rootNode) {
        if (rootNode == null) {
            return;
        }
        System.out.print(rootNode.val);
        preOrderRecursion(rootNode.left);
        preOrderRecursion(rootNode.right);
    }
}

class TreeNode {
    char val;
    TreeNode left;
    TreeNode right;

    public TreeNode(char val) {
        this.val = val;
    }
}
